#########
#### Replication codes
# A Dyadic Method to Investigate Voting Behaviour in the Council of the European Union
# Install packages
install.packages("tidyverse")
install.packages("corrr")
install.packages("stargazer")
install.packages("gridExtra")
install.packages("reshape2")

# R version: 
library(tidyverse)
library(corrr)
library(stargazer)
library(gridExtra)
library(reshape2)
#######################################################################
################# Descriptive Analysis  ###############################
#######################################################################

# Reading the dataset
EU_NET_NPexcluded <- read_csv("Dyadic_3d.csv")
#
# TABLE 1
#
pair_split <- do.call(rbind, strsplit(as.character(EU_NET_NPexcluded$pair_decision), " "))

# Sort the components alphabetically for each pair
sorted_pairs <- apply(pair_split, 1, function(x) paste(sort(x), collapse = " "))

# Add the reordered pairs back to the data frame
EU_NET_NPexcluded$sorted_pair <- as.factor(sorted_pairs)

# Summarize the counts for the reordered pairs
table_1 <- as.data.frame(table(EU_NET_NPexcluded$sorted_pair))

# Calculate the percentage share of each pair
table_1$Share <- (table1$Freq / sum(table1$Freq)) * 100

# Rename columns for clarity
colnames(table_1) <- c("Pair", "Count", "Share (%)")

# Print the table
print(table_1)
#
# TABLE 2
EU_NET_NPexcluded$Binary_Decision_same <- as.factor(EU_NET_NPexcluded$Binary_Decision_same)
ftable(EU_NET_NPexcluded$Binary_Decision_same)
table_2 <- prop.table(table(EU_NET_NPexcluded$Binary_Decision_same))
print(table_2)
# TABLE 3
EU_NET_NPexcluded$Decision_Same <- as.factor(EU_NET_NPexcluded$Decision_Same)
ftable(EU_NET_NPexcluded$Decision_Same)
table_3 <- prop.table(ftable(EU_NET_NPexcluded$Decision_Same))
print(table_3)
# TABLE 4
EU_NET_NPexcluded$Decision_Distance <- as.factor(EU_NET_NPexcluded$Decision_Distance)
ftable(EU_NET_NPexcluded$Decision_Distance)
table_4 <- prop.table(table(EU_NET_NPexcluded$Decision_Distance))
print(table_4)

# TABLE 6 
summary(EU_NET_NPexcluded$LEFT_RIGHT)
##
summary(EU_NET_NPexcluded$LIBERTY_AUTHORITY)
###
summary(EU_NET_NPexcluded$EU_ANTI_PRO)
#
EU_NET_BOX <- EU_NET_NPexcluded %>%
  select(id, LEFT_RIGHT, LIBERTY_AUTHORITY, EU_ANTI_PRO)
#
EU_NET_BOX_Long <- EU_NET_BOX %>%
  gather(key = Dimension, value = Distance, LEFT_RIGHT:EU_ANTI_PRO)
#
EU_NET_BOX_Long$Dimension <- as.factor(EU_NET_BOX_Long$Dimension)
levels(EU_NET_BOX_Long$Dimension)
#
EU_NET_BOX_Long$Dimension <- factor(EU_NET_BOX_Long$Dimension,
                                    levels = c("LEFT_RIGHT", 
                                               "LIBERTY_AUTHORITY", "EU_ANTI_PRO"))
#
levels(EU_NET_BOX_Long$Dimension)
#
#
EU_NET_BOX <- as.data.frame(EU_NET_BOX)
#
stargazer(EU_NET_BOX,
          type = "html",
          out = "Descriptive_Statistics.doc")
##


#
#
#
#
# FIGURE 1
##### I want to create a boxplot for all variables together:

#
Figure_1 <- EU_NET_BOX_Long %>% 
  ggplot() +
  geom_boxplot(aes(y = Distance, x = Dimension, fill = Dimension)) +
  labs(x = "",
       y = "",
       title = "",
       subtitle = "") +
  theme_bw() +
  theme(legend.position = "none",
        plot.title = element_text(size = 10),        # Change title font size
        plot.subtitle = element_text(size = 10),     # Change subtitle font size
        axis.title.x = element_text(size = 10),      # Change x-axis title font size
        axis.title.y = element_text(size = 10),      # Change y-axis title font size
        axis.text.x = element_text(size = 10),       # Change x-axis text font size
        axis.text.y = element_text(size = 10)        # Change y-axis text font size
  ) +
  scale_fill_manual(values = c("grey", "grey", "grey"))
#
ggsave("Figure_1_3d.eps", plot = Figure_1, device = "eps", width = 6.5, height = 5, dpi = 400)
#
# Figure 2
#
p1 <- ggplot(EU_NET_BOX) +
  geom_point(mapping = aes(x = LEFT_RIGHT, y = LIBERTY_AUTHORITY), alpha = 0.01) +
  theme_bw() +
  labs(x = "Left-right",
       y = "Liberty-authority",
       title = "",
       subtitle = "") +
  theme(
    legend.position = "none",
    plot.title = element_text(size = 10),        # Change title font size
    plot.subtitle = element_text(size = 10),     # Change subtitle font size
    axis.title.x = element_text(size = 12),      # Change x-axis title font size
    axis.title.y = element_text(size = 12),      # Change y-axis title font size
    axis.text.x = element_text(size = 10),       # Change x-axis text font size
    axis.text.y = element_text(size = 10)        # Change y-axis text font size
  )
#
p2 <- ggplot(EU_NET_BOX) +
  geom_point(mapping = aes(x = LEFT_RIGHT, y = EU_ANTI_PRO), alpha = 0.01) +
  theme_bw() +
  labs( x = "Left-right",
        y = "EU anti-pro",
        title = "" ,
        subtitle = "") +
  theme(
    legend.position = "none",
    plot.title = element_text(size = 10),        # Change title font size
    plot.subtitle = element_text(size = 10),     # Change subtitle font size
    axis.title.x = element_text(size = 12),      # Change x-axis title font size
    axis.title.y = element_text(size = 12),      # Change y-axis title font size
    axis.text.x = element_text(size = 10),       # Change x-axis text font size
    axis.text.y = element_text(size = 10)        # Change y-axis text font size
  )
#
p3 <- ggplot(EU_NET_BOX) +
  geom_point(mapping = aes(x = LIBERTY_AUTHORITY, y = EU_ANTI_PRO), alpha = 0.01) +
  theme_bw() +
  labs( x = "Liberty-authority",
        y = "EU anti-pro",
        title = "" ,
        subtitle = "") +
  theme(
    legend.position = "none",
    plot.title = element_text(size = 10),        # Change title font size
    plot.subtitle = element_text(size = 10),     # Change subtitle font size
    axis.title.x = element_text(size = 12),      # Change x-axis title font size
    axis.title.y = element_text(size = 12),      # Change y-axis title font size
    axis.text.x = element_text(size = 10),       # Change x-axis text font size
    axis.text.y = element_text(size = 10)        # Change y-axis text font size
  )
#

#
Figure_2 <- grid.arrange(p1, p2, p3, ncol = 2)
#
ggsave("Figure_2_3d.jpeg", plot = Figure_2,  width = 6.5, height = 7, dpi = 400)
#
# FIGURE 3 
Figure_3 <- EU_NET_NPexcluded %>%
  ggplot(aes(x = Euclidean)) +
  geom_histogram(colour = 4, boundary=0, fill = "white") +
  theme_bw() +
  theme(
    legend.position = "none",
    plot.title = element_text(size = 12),        # Change title font size
    plot.subtitle = element_text(size = 12),     # Change subtitle font size
    axis.title.x = element_text(size = 12),      # Change x-axis title font size
    axis.title.y = element_text(size = 12),      # Change y-axis title font size
    axis.text.x = element_text(size = 12),       # Change x-axis text font size
    axis.text.y = element_text(size = 12)        # Change y-axis text font size
  ) +
  labs(x = "Euclidean distance",
       y = "Frequency",
       title = "",
       subtitle = "") 
#
ggsave("Figure_3_3d.png", plot = Figure_3, dpi = 300)
ggsave("Figure_3_3d.eps", plot = Figure_3, device = "eps", width = 6.5, height = 4.5, dpi = 400)
####
#
#
#
#
#

########################################################################
# Figure S.1 (in the supplementary materials)
#
EU_NET <- read_csv("Dyadic_3d.csv")

#
names(EU_NET)
#
### A dataframe that shows total number of times to MS voted together & how many times their decisions were the same
Pair_similarity <- EU_NET %>%
  group_by(Country_A, Country_B) %>%
  summarize(Total_votes_together = length(Decision_Same),
            Total_same_decisions = sum(Decision_Same)) %>%
  ungroup()
#
Pair_similarity$Total_votes_together <- as.numeric(Pair_similarity$Total_votes_together)
Pair_similarity$Total_same_decisions <- as.numeric(Pair_similarity$Total_same_decisions)
#
#
Pair_similarity <- Pair_similarity %>%
  mutate(Similarity_decision = 100 * Total_same_decisions / Total_votes_together)
#
#
### A dataframe that shows total number of times to MS voted together & how many times their decisions were the same in each YEAR
Pair_similarity_Year <- EU_NET %>%
  group_by(Country_A, Country_B, Decision_Year) %>%
  summarize(Total_votes_together = length(Decision_Same),
            Total_same_decisions = sum(Decision_Same)) %>%
  ungroup()
#
Pair_similarity_Year <- Pair_similarity_Year %>%
  mutate(Similarity_decision = 100 * Total_same_decisions / Total_votes_together)
# 



### A dataframe that shows total number of times to MS voted together & how many times their decisions were the same in each POLICY AREA

Pair_similarity_PolicyArea <- EU_NET %>%
  group_by(Country_A, Country_B, POLICY_AREA) %>%
  summarize(Total_votes_together = length(Decision_Same),
            Total_same_decisions = sum(Decision_Same)) %>%
  ungroup()
#
Pair_similarity_PolicyArea <- Pair_similarity_PolicyArea %>%
  mutate(Similarity_decision = round(100 * Total_same_decisions / Total_votes_together, 2))

#
####################################################
################# Matrix    ########################
####################################################
PAIR <- Pair_similarity %>%
  dplyr::select(Country_A, Country_B, Similarity_decision)
#
PAIR2 <- PAIR
#
PAIR2$Country_A <- PAIR$Country_B
PAIR2$Country_B <- PAIR$Country_A
#
PAIR <- rbind(PAIR, PAIR2)
#
Pair_MATRIX <- dcast(PAIR, Country_A ~ Country_B, value.var = "Similarity_decision", fill = 0)
####################################################
################# Heatmaps  ########################
####################################################
# Now, I wanna create a heatmap
Pair_MATRIX_Melt <- melt(Pair_MATRIX)
# A few edits before the heatmap
names(Pair_MATRIX_Melt)[2] <- "Country_B"
names(Pair_MATRIX_Melt)[3] <- "Similarity"
#
Pair_MATRIX_Melt <- Pair_MATRIX_Melt %>%
  mutate( Similarity = case_when(Country_A == Country_B ~ 100,
                                 Country_A != Country_B ~ Similarity))
#
Pair_MATRIX_Melt$Similarity <- round(Pair_MATRIX_Melt$Similarity, digits = 2)
#
ggplot(Pair_MATRIX_Melt, aes(Country_A, Country_B)) +
  geom_tile(aes(fill = Similarity)) +
  geom_text(aes(label = Similarity))
# 
# tirangle heatmap
Pair_MATRIX_2 <- Pair_MATRIX %>%
  select(-Country_A)



get_upper_tri <- function(Pair_MATRIX_2){
  Pair_MATRIX_2[lower.tri(Pair_MATRIX_2)]<- NA
  return(Pair_MATRIX_2)
}
#
Pair_MATRIX_upper_tri <- get_upper_tri(Pair_MATRIX_2)
#
Pair_MATRIX_Melt_2 <- melt(Pair_MATRIX_upper_tri)
#
Pair_MATRIX_Melt_2$Country_A <- Pair_MATRIX_Melt$Country_A
Pair_MATRIX_Melt_2$Country_B <- Pair_MATRIX_Melt$Country_B
Pair_MATRIX_Melt_2$Similarity <- Pair_MATRIX_Melt_2$value
#
Pair_MATRIX_Melt_2 <- Pair_MATRIX_Melt_2 %>%
  select(Country_A, Country_B, Similarity)
#
Pair_MATRIX_Melt_2 <- Pair_MATRIX_Melt_2 %>%
  mutate( Similarity = case_when(Country_A == Country_B ~ 100,
                                 Country_A != Country_B ~ Similarity))
#
Pair_MATRIX_Melt_2$Similarity <- round(Pair_MATRIX_Melt_2$Similarity, digits = 0)
#
#
Alignment_Matrix <- ggplot(Pair_MATRIX_Melt_2, aes(Country_A, Country_B)) +
  geom_tile(aes(fill = Similarity), color = "white") +
  geom_text(aes(label = Similarity), size = 2.5) +
  scale_fill_gradient(low = "lightblue", high = "lightsteelblue") +
  theme(axis.text.y = element_text(angle = 0, hjust = 0.5, vjust = 0.5, size = 8)) +
  theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust = 0.5, size = 8)) +
  labs(x = NULL, y = NULL)
#
print(Alignment_Matrix)
#
ggsave("Alignment_Matrix.eps", plot = Alignment_Matrix, device = "eps", width = 6.5, height = 6.5, dpi = 400)

